<template>
  <div id="container" @mouseup="endDrag" @mousemove="trackMouse">
    <div ref="div1" class="div_1"><content1 /></div>
    <div ref="div2" class="div_2" @mousedown="startDrag">
      <img style="pointer-events: none" src="../../assets/drag.png" />
    </div>
    <div ref="div3" class="div_3"></div>
  </div>
</template>
<script setup>
import {
  onMounted,
  getCurrentInstance,
  defineProps,
  nextTick,
  ref,
  defineEmits,
} from "vue";
import { setHead } from "@/utils/setHead";
import content1 from "./content1.vue";

const bus = getCurrentInstance().appContext.config.globalProperties.$bus;

const emits = defineEmits(["child-event"]);

const div1 = ref(null);

const div2 = ref(null);

let dragging = false; //控制是否能拖动

let startX = 0; //拖动时的横左边

let containerWidth = ""; //container容器的宽度

const props = defineProps({
  dynamicWidth: String,
});

const countWidth = () => {
  //设置div1的宽度
  const width = props.dynamicWidth.substring(
    0,
    props.dynamicWidth.indexOf("v")
  );
  const widthNum = Number(width);
  const divWidth = widthNum + (6 / containerWidth) * 100;
  div1.value.style.width = divWidth + "vw";
};

const startDrag = (e) => {
  console.log("startDrag");
  dragging = true;
  startX = e.clientX;
};

const trackMouse = (e) => {
  if (dragging) {
    const deltaX = e.clientX - startX;
    startX = e.clientX;
    const oldWidth =
      (div1.value.style.width.substring(
        0,
        div1.value.style.width.indexOf("v")
      ) *
        window.innerWidth) /
      100; //原来的div1的宽度
    const newWidth = ((oldWidth + deltaX) / window.innerWidth) * 100 + "vw";
    div1.value.style.width = newWidth;
    //通知父组件改变父组件的宽度
    emits("child-event", newWidth);
  }
};

const endDrag = () => {
  console.log("endDrag");
  dragging = false;
};

onMounted(() => {
  //监听全局事件总线
  bus.on("head", (msg) => {
    setHead(document.querySelector("#container"), msg, 13);
  });
  nextTick(() => {
    containerWidth = document.getElementById("container").offsetWidth;
    countWidth();
  });
});
</script>
<style scoped>
#container {
  background-color: white;
  display: flex;
  flex: 1;
  margin-left: 1vw;
}
.div_1 {
  border: 1px solid #aaaaaa;
  border-radius: 1px;
  background-color: aquamarine;
}
.div_2 {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 6px;
  cursor: col-resize;
}
.div_3 {
  flex: 1;
  border: 1px solid #aaaaaa;
  border-radius: 1px;
  background-color: azure;
}
</style>
